/// <reference path="../../typings/index.d.ts" />
'use strict';

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Article = mongoose.model('Article');
const Task = mongoose.model('Task');
const apiHandler = require('../handlers/apiHandler');
const auth = require('../handlers/authHandler');
// import { listHandler } from './apiHandler';
module.exports = function(app) {
    app.use('/', router);
};

router.get('/task', auth.auth, (req, res, next) => {
    Task.find((findErr, tasks) => {
        if (findErr) {
            return res.json({
                err: { msg: '查找时出现错误！！', err: findErr },
                data: null
            })
        }
        next();
    })
}, apiHandler.listHandler);
router.delete('/task/:taskId', auth.auth, (req, res, next) => {
    Task.remove({
        _id: req.params.taskId
    }, (removeErr, task) => {
        if (removeErr) {
            return res.json({
                err: { msg: '删除错误', err: removeErr },
                data: null
            })
        }
        next();
    })
}, apiHandler.listHandler);
/** */
router.post('/update', auth.auth, (req, res, next) => {
    const { _id, task, Person, complete } = req.body;
    Task.findById(_id, function(err, t) {
        t.task = task;
        t.complete = complete;
        t.UpdateyTime = Date.now();
        Task.update({ _id: _id }, t, err => {
            if (err) {
                return res.json({
                    msg: 'update err',
                    err: err
                });
            }
            return res.json({
                msg: 'update ok',
                err: null
            });
        });
    });
});
router.post('/search', auth.auth, apiHandler.findByStr);
router.post('/task', function(req, res, next) {
    let t = new Task({
        task: req.body.task,
        Person: 'getsai',
        CreateTime: Date.now(),
        UpdateTime: Date.now(),
        complete: false,
    });
    t.save(err => {
        if (err) {
            return res.json({
                    err: err,
                    data: null
                })
                // return next(err);
        };
        next()
    })
}, apiHandler.listHandler);